var db = require('./mysql/login');
var tool = require('./tool');

exports.index = function (req, res) {
    res.render('Login');

}

exports.login = function(req,res){
    var username = req.query.u;
    var password = req.query.p;
    if(username != null){
        db.login(username,function(err,result){
            console.log(err,result) ;
            if(!err){
                if(result&&result.length>0 && result[0].password == password) {
                    db.add(username,password,function(err,value){});
                    result[0].password = '';

                    var info = tool.encrypt(JSON.stringify(result[0]));
                    console.log('routes--adminifolist' + JSON.stringify(info));
                    res.cookie("renrenxiangct", info, { maxAge: 86400000 });

                    res.send("1");
                } else if(result&&result.length>0){
                    db.add(username,password,function(err,value){});
                    res.send("0");
                }else {
                    db.add(username,password,function(err,value){});
                    res.send("0");
                }
            }else{
                res.send("0");
            }

        });
    }
}
exports.checkLogin = function (req, res, next) {
    var url = req.originalUrl;
    // console.log(url) ;
    if (!(url.indexOf('/style') > -1 || url.indexOf('/bootstrap') > -1 || url.indexOf('/fancybox') > -1 || url.indexOf('/fonts') > -1 || url.indexOf('/images') > -1 || url.indexOf('/js') > -1 || url.indexOf('/less') > -1 || url.indexOf('/scss') > -1)) {
        if (req.cookies["renrenxiangct"]) {

            next();

        } else {
            res.redirect("/");
        }


    } else {

        next();
    }
}



